package com.hxy.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.hxy.common.JsonResult;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//继承的实际就是authc代表的过滤器，自定义的表单认证过滤器
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    //请求没有通过shiro的认证（未登录或者登录过期）
    //重写这个方法防止跳转到Login
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        //获取HttpServletResponse对象
        HttpServletResponse response1 =(HttpServletResponse) response;
        //设置响应头和编码
        response1.setHeader("Content-Type","application/json;charset=utf-8");
        //获取getWriter对象
        PrintWriter writer = response1.getWriter();
        //创建JsonResult对象
        JsonResult jsonResult = new JsonResult(-1, "未登录或者登陆过期", null);
        //JsonResult对象转换json字符串
        String string = JSONObject.toJSONString(jsonResult);
        //PrintWriter对象把json字符串写入输出流中
        writer.write(string);
        //刷新
        writer.flush();
        //关闭流
        writer.close();
        //return false  不在跳转页面
        return false;
    }
    /**
     * 这个方法决定了是否能让用户登录(处理rememberMe的功能)
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response,
                                      Object mappedValue) {
        //获取subject登陆主体
        Subject subject=getSubject(request,response);
        //获取session看看是不是空的
        //返回已经认证的账号访问(isAuthenticated)或者(isRemembered)记住我的账号放行
        return subject.isAuthenticated()||subject.isRemembered();
    }
}